import {request} from '../../utils/http'

Page({
  data: {
    product: {},
    stageList: [],
    hasMore: false,
    isExpand: false,
    max: 6,
    member: {
      id: '',
      mobile: '',
      name: '',
      token: '',
      cert_no:''
    },
    storeId: 0,
    isLoadPlugin: false,
    order: {},
    info: {},
    invite_code:'',
    invite_required:false,
    invite_show:false,
    is_scan:false,
    price:'',
    remark:'',
    is_edit:false,
    smid:'',
    show:false,
    pay_type:'alipay',
    huabei:'',
    stageType:'',
    stage:'',
    id:'',
    mixed_price:''
  },
  radioChange(e){
    console.log(e)
    let huabei = this.data.huabei
    this.setData({
      pay_type:e.detail.value,
      huabei: e.detail.value == 'alipay' ? '' : huabei
    })
  },
  onLoad(query) {
    // 页面加载
    console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
   
    let is_scan = this.data.is_scan;
    if (!query.id) {
      // 二维码直接进入时，取二维码参数
      query = my.getEnterOptionsSync().query;
      is_scan = true
    } else {
      if (query.is_scan == 'true') {
        is_scan = true;
      } else {
        is_scan = false
      }
    }

    // is_scan = query.is_scan || false;
    let price = this.data.price;
    let remark = this.data.remark
    if (query.edit) {
      price = query.price;
      remark = query.remark;
    }
    
    this.setData({
      storeId: query.storeId,
      is_scan,
      is_edit: query.edit,
      stage: query.stage,
      stageType:query.stageType,
      mixed_price:query.mixed_price,
      price,
      remark,
      id:query.id
    },() => {
      this.fetch(query.id)

    })
  },
  onReady() {
    // 页面加载完成
  },
  onShow() {
    // 页面显示
    my.getStorage({
      key: 'userInfo',
      success: (res) => {
        console.log(res)
        if (res.data) {
          this.setData({
            member: res.data,
          })
        }
      }
    });
  },
  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      // title: '微蓝辅导',
      // desc: '微蓝辅导',
      path: 'pages/index/index',
    };
  },
  huabeiItemClick(e){
    // if (this.data.pay_type == 'alipay') {
    //   return
    // }
    let { item } = e.currentTarget.dataset

    this.setData({
      huabei: item.stage,
      pay_type:'huabei'
    })
  },
  fetch(id) {
    let params = {
      store_id:this.data.storeId
    }
    if (this.data.price) {
      params['price'] = this.data.price
    }

    if (this.data.stageType == 1 || this.data.stageType == 2) {
      params['user_total_stage'] = this.data.stage
    }

    if (this.data.mixed_price) {
      params['mixed_order_pre_price'] = this.data.mixed_price

    }
    
    request('/order/preview/' + id, 'get', params).then(res => {
      if (res.code == 200) {
        let product = res.data.product;
        let shop_id = res.data.product.shop.id
        this.getConfig(shop_id)
        if (!this.data.is_edit) {
          if (res.data.product.price_is_edit == 1) {
            my.redirectTo({
              url: `/pages/updateProductPrice/updateProductPrice?id=${id}&storeId=${this.data.storeId}&is_scan=true`
            })
            return;
          }
        } 
        if (this.data.price) {
          product.price = this.data.price;
          
        }

        if (this.data.remark) {
          product.remark = this.data.remark
        }

        // if (product.pay_method == 3) {
        //   my.setNavigationBar({
        //     title:'商品下单',
        //   })
        // } else{
        //   my.setNavigationBar({
        //     title:'先享后付',
        //   })
        // }

        // if (product.shop.shop_pay_type == 3 || product.shop.shop_pay_type == 2) {
        //   my.setNavigationBar({
        //     title:'商品下单',
        //   })
        // }
          

        this.setData({
          info:res.data,
          invite_required: res.data.invite_required == 1 ? true : false,
          invite_show: res.data.invite_show == 1 ? true : false,
          product: product,
          stageList: res.data.stageList,
          hasMore: res.data.stageList.length > this.data.max ? true : false
        }, () => {
          if (this.data.product.pay_method != 3) {
            request('/shop/smid','get', {shop_id:shop_id}).then(res => {
              if (res.code == 200) {
                this.setData({
                  smid:res.data.smid
                },() => {
                    this.loadPlugin()

                })
              }
            });
          }

        })
      }
     
    })
  },
  goZM4(data){
    const accountInfo = my.getAccountInfoSync();
    const targetUrl = encodeURIComponent('/pages/zhima-result/zhima-result');
    let url =`/pages/cycle-card-buy/index?spcTemplateId=${data.card_template_id}&outOrderNo=${data.out_order_no}&shopId=${data.zm_shop_id}&jumpType=merchant&appId=${ accountInfo.miniProgram.appId || ''}&targetUrl=${targetUrl}`
    if (data.card_property_id) {
      url = `${url}&propertyId=${data.card_property_id}`
    }
    // return
    my.navigateToMiniProgram({
      appId: '2021004147687320',
      path: url,
      success: () => {
        console.log('navigateToMiniProgram success');
      },
      fail: res => {
        my.alert({
          title: 'navigateToMiniProgram fail',
          content: JSON.stringify(res),
        });
      },
    });
  },
  handleExpand() {
    this.setData({
      isExpand: true
    })
  },
  handleReduce() {
    this.setData({
      isExpand: false
    })
  },
  onGetAuthorize(res) {
    console.log(111111);
  },

   /**
  *	初始化数据 - 宿主传参
  */

  loadPlugin() {
    console.log('loadPlugin')
    my.loadPlugin({
      plugin: '2021003126645865@*', // 指定要加载的插件id和版本号，为 * 时自动选择版本
      success: () => {
        // 初始化数据 - 宿主传参
        console.log('success')
        this.setData({
          isLoadPlugin: true
        })
      },
      fail: (err) => {
        console.log(err)
      }
    });
  },

 initData(order) {
    // 引用插件实例
    const plugin = requirePlugin('dynamic-plugin://2021003126645865');
    // const ext = my.getExtConfigSync()
    // console.log(ext.pid)
    
    // 宿主向插件传参数，通过实例调用init方法传参
    console.log(this.data.product, 'product');
    let d = new Date();
    // 开通
    const options = {
      merchantPid: this.data.smid, // 必传 - 商户PID
      productNo: order.product_id, // 必传 - 产品编号
      
      subscriptionType: order.pay_date == 1 ? 'MONTH' : 'WEEK', // 非必填, 订购类型, 默认为月卡
      productName: order.product_title, //必传 - 产品名称
      deductionAmount: order.second_amount, // 必传 - 每次扣减固定金额
      periods: order.total_stage, // 必传 - 开通总周期数
      downPayment: order.first_amount, // 非必填 - 前N期金额
      downPaymentPeriods: order.first_stage, // 非必填 -前多少期价格不一样，不传默认为1
      downPaymentDate: this.data.stageList[0].date,
      outSubscriptionNo: order.out_order_no
    }

    if (this.data.product.ant_shopid) {
      options['shopId'] = this.data.product.ant_shopid
    }
    console.log('options', options)
    plugin.init({
      openOptions: options
    });
  
    //plugin.setEnv('dev');
    
    // 查询
    // plugin.init({
    //   queryOptions: {
    //      merchantPid: '2088242756693907', // 必传 - 商户PID
    //      productNo: '666', // 必传 - 产品编号
    //      subscriptionNo: 'S20220429174648000000000000096364', //必传 - 订购编号
    //   }
    // })
  },
/**
*	调用跳转方法
*/
navigateToPluginPage(order) {
  if (!this.data.isLoadPlugin) {
    my.showToast({content: '插件加载失败'})
    return;
  }
  this.initData(order)
  // 跳转至插件首页
  my.navigateTo({
    url: 'dynamic-plugin://2021003126645865/index'
  })
},
alipaySubmit(){
  let params =  {
    product_id: this.data.product.id, 
    name: this.data.member.name,
    price: this.data.product.price,
    remark: this.data.product.remark,
    invite_code:this.data.invite_code,
    cert_no: this.data.member.cert_no,
    store_id: this.data.storeId
  }

  if (this.data.pay_type == 'huabei') {
    if (this.data.huabei){
      params['huabei_stage']  = this.data.huabei

    } else {
      my.showToast({content: '请选择花呗分期'});
      return;
    }
  }

  if (this.data.stageType == 1 || this.data.stageType == 2) {
    params['user_total_stage'] = this.data.stage
  }
  var self = this
  request('/order/create', 'post', params).then(res => {
    if (res.code == 200) {
      let trade_no = res.data.order_no;
      my.tradePay({
        tradeNO:trade_no,
        success(result) {
          if (result.resultCode == '9000') {
            self.getOrderStatus(res.data.id)
          } else {
            my.showToast({ content: result.memo });
          }
        },
        fail(error){
          console.log(error,'error')
        }
      })
    } else {
      my.showToast({content: res.message});

    }
  })
},
submit() {
    if (typeof this.data.order.id !== 'undefined') {
      my.navigateTo({
        url: '../orderDetail/index?id=' + this.data.order.id
      })
      return;
    }
    let mobile_login = my.getStorageSync({key:'mobile_login'}).data
    console.log(mobile_login)
    if (!this.data.member.mobile) {
      if (mobile_login == 1) {
        my.navigateTo({
          url:'/pages/login-by-phone/login-by-phone'
        })
      } else {
        my.navigateTo({
          url:'/pages/login/login'
        })
      }
     
      my.showToast({content: '请先登录'});
      return;
    }
    
    if (!this.data.member.name) {
      my.showToast({content: '请输入姓名'});
      return;
    }

    if ((this.data.product.pay_method  == 1 || this.data.product.pay_method  == 2)) {
      if (!this.data.member.cert_no) {
        my.showToast({content: '请输入身份证号码'});
        return;
      }
    }

    if (this.data.invite_required ) {
      if (!this.data.invite_code) {
        my.showToast({content: '请输入邀请码'});
        return;
      }
    }
  
    my.setStorage({
      key: 'userInfo',
      data: {
        ...this.data.member,
      },
      success: function() {
        console.log('缓存写入成功')
      }
    });
    let self = this;
    console.log(self.data.product,'sss')
    request('/order/checkReOrder', 'get', {
      product_id:this.data.product.id,
      name: this.data.member.name,
      cert_no: this.data.member.cert_no,
      mobile:this.data.member.mobile
    }).then(res => {
      if (res.code == 200) {
        if (res.data.isExists == 1) {
          my.confirm({
            title:'重复下单提醒',
            content:res.data.msg,
            confirmButtonText:'不下单了',
            cancelButtonText:'我想继续下单',
            success(result){
              if (!result.confirm) {
                // if (self.data.product.shop.shop_pay_type == 2  && self.data.product.pay_method != 3) {
                //   my.navigateTo({
                //     url:`/pages/blockchain-detail/blockchain-detail?id=${self.data.id}&product_id=${self.data.product.id}&name=${self.data.member.name}&price=${self.data.product.price}&remark=${self.data.product.remark || ''}&invite_code=${self.data.invite_code}&cert_no=${self.data.member.cert_no}&store_id=${self.data.storeId}&stage=${self.data.stage}&stageType=${self.data.stageType}`
                //   })
                // } else {
                  if (self.data.product.pay_method == 3) {
                    this.setData({
                      show:true
                    })
                  } else {
                    self.createOrder();

                  }
      
                // }
              }
            }
          })
        } else {
          // if (this.data.product.shop.shop_pay_type == 2 && this.data.product.pay_method != 3) {
          //   my.navigateTo({
          //     url:`/pages/blockchain-detail/blockchain-detail?id=${this.data.id}&product_id=${self.data.product.id}&name=${this.data.member.name}&price=${this.data.product.price}&remark=${this.data.product.remark || ''}&invite_code=${this.data.invite_code}&cert_no=${this.data.member.cert_no}&store_id=${this.data.storeId}&stage=${this.data.stage}&stageType=${this.data.stageType}`
          //   })
          // } else {
            if (self.data.product.pay_method == 3) {
              this.setData({
                show:true
              })
            } else {
              self.createOrder();

            }

          }
        // }
      } else {
        my.showToast({content: res.message});
        if (res.code == 403) {
          my.navigateTo({
            url: '/pages/login/login'
          })
        }
      }
    })
    
  },
  getOrderStatus(order_id){
    request('/order/' + order_id, 'get', {queryStatus:1}).then(res => {
      if (res.code == 200) {
        my.redirectTo({
          url: `/pages/pay-result/pay-result?id=${order_id}&status=${res.data.status}`
        })
      }
    })
  },
  createOrder(){
    let self = this;
    let params = {
      product_id: this.data.product.id, 
      name: this.data.member.name,
      price: this.data.product.price,
      remark: this.data.product.remark,
      invite_code:this.data.invite_code,
      cert_no: this.data.member.cert_no,
      store_id: this.data.storeId
    }

    if (this.data.stageType == 1 || this.data.stageType == 2) {
      params['user_total_stage'] = this.data.stage
    }

    if (this.data.mixed_price) {
      params['mixed_order_pre_price'] = this.data.mixed_price

    }

    request('/order/create', 'post', params).then(res => {
        if (res.code == 200) {
          my.setStorageSync({key:'is_skip_bindcard',data:res.data.is_skip_bindcard || 0})
          // this.navigateToPluginPage(res.data)

          if (res.data.mixed_order == 1) {
            if (res.data.jump_type == 1) {
              let trade_no = res.data.trade_no;
              my.tradePay({
                  tradeNO:trade_no,
                  success(result) {
                    console.log(result)
                    request('/order/stage/pay_result/' + res.data.stage_list[0].id, 'get', {queryStatus:1}).then(orderRes => {
                      if (orderRes.code == 200) {
                          my.navigateTo({
                            url:`/pages/mixed-result/mixed-result?status=${orderRes.data.status}&id=${self.data.id}&order_no=${res.data.id}&price=${self.data.info.product.mixed_order_pre_price}`
                          })
                      }
                    })
                    
                   
                  },
                  fail(error){
                    console.log(error,'error')
                    my.navigateTo({
                      url:`/pages/mixed-result/mixed-result?status=50&id=${self.data.id}&order_no=${res.data.id}`
                    })
                  }
              })
            }
          } else {
            if (this.data.product.pay_method == 3) {
              let trade_no = res.data.order_no;
              my.tradePay({
                tradeNO:trade_no,
                success(result) {
                  console.log(result,'success')
                  // self.getOrderStatus(res.data.id)
                  if (result.resultCode == '9000') {
                    self.getOrderStatus(res.data.id)
                  } else {
                    my.showToast({ content: result.memo });
                  }
                },
                fail(error){
                  console.log(error,'error')
                }
              })
              
            }  else {
              this.setData({
                order: res.data
              })
              let aiqian_zm = my.getStorageSync({key:'aiqian_zm'}).data
              if (aiqian_zm == 1) {
                my.setStorageSync({
                  data: res.data.id,
                  key: 'sign_order_id'
                });

                my.removeStorageSync({key:'sign_order_type'});

                my.navigateTo({
                  url:`/pages/sign-webview/sign-webview?url=${res.data.contract_signurl}`
                })
               
              } else {
                if (res.data.version == 1) {
                  this.navigateToPluginPage(res.data)

                } else if (res.data.version == 4){
                  this.goZM4(res.data)
                }
  
                
              }
            }
          }   
         
        } else {
          my.showToast({content: res.message});

        }
    
    })
  },
  bindKeyInputName(e) {
    this.setData({
      member: {
        ...this.data.member,
        name: e.detail.value
      },
    });
  },
  bindKeyInputCardNo(e) {
    this.setData({
      member: {
        ...this.data.member,
        cert_no: e.detail.value
      },
    });
  },
  bindKeyInviteCode(e){
    this.setData({
      invite_code:e.detail.value
    })
  },
  myOrder(){
    if (!this.data.member.mobile) {
      my.navigateTo({
        url:'/pages/login/login'
      })
      my.showToast({content: '请登录后再操作'});
      return;
    }
    if (this.data.product.pay_method != 3) {
      my.navigateTo({
        url: '/pages/order/index?pay_method=3',
      })
    } else {
      my.navigateTo({
        url: '/pages/full-order/full-order?pay_method=1',
      })
    }
  },
  async getConfig(shop_id) {
    let res = await request('/shop/getSwitchConfigs','get', {shop_id: shop_id})
    if (res.code === 200) {
      console.log(res.data)
      // this.globalData.logo = res.data.app_logo
      // this.globalData.mobile_login = res.data.mobile_login

      my.setStorage({
        key:'supplier_id',
        data: res.data.supplier_id
      })

      my.setStorage({
        key: 'mobile_login',
        data: res.data.mobile_login,
        
      })

      my.setStorage({
        key: 'chain_initiative_pay',
        data: res.data.chain_initiative_pay,
        
      })

      my.setStorage({
        key: 'zm_initiative_pay',
        data: res.data.zm_initiative_pay,
        
      })
      

      my.setStorage({
        key: 'card_initiative_pay',
        data: res.data.card_initiative_pay,
        
      })

      my.setStorage({
        key: 'after_sales_hidden',
        data: res.data.after_sales_hidden,
        
      })

      my.setStorage({
        key: 'aiqian_zm',
        data: res.data.aiqian_zm,
        
      })

      my.setStorage({
        key: 'aiqian_card',
        data: res.data.aiqian_card,
        
      })

      my.setStorage({
        key:'kefu_show',
        data: res.data.kefu_show
      })

      my.setStorage({
        key:'card_pay_identity_no_required',
        data: res.data.card_pay_identity_no_required 
      })
      

      my.setStorage({
        key:'appointment_entrance',
        data: res.data.appointment_entrance 
      })
      
      
    }
  }

});
